<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\shop_admin\service;

use app\shop_admin\model\AttrName;
use app\shop_admin\model\AttrName as admin;
use app\shop_admin\model\AttrValue;

class AttrService
{

    /**
     * @param $commodityId
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($commodityId)
    {
        $list = admin::field('id,name,has_pic')
            ->where('commodity_id',$commodityId)
            ->with('attrValue')
            ->select();

        return $list;
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(int $commodityId,array $data)
    {
        foreach ($data as $k => $v) {
            $v['commodity_id'] = $commodityId;
            $attrName = admin::create($v);
            $attrName->attrValue()->saveAll($v['attrValue']);
        }
        return [HTTP_CREATED, "成功"];
    }

    public function update(int $commodityId,array $data)
    {
        $ids = array_column($data, 'id');
        !empty($ids) && admin::whereNotIn('id', $ids)->where(['commodity_id'=>$commodityId])->delete();
        foreach ($data as $k => $v) {
            $ids = array_column($v['attrValue'], 'id');
            !empty($ids) && AttrValue::whereNotIn('id', $ids)->where(['attr_name_id'=>$v['id']])->delete();
            $v['commodity_id'] = $commodityId;
            if (isset($v['id'])){
                admin::update($v,['id'=>$v['id']]);
                foreach ($v['attrValue'] as $i=>$j){
                    $j['attr_name_id'] = $v['id'];
                    isset($j['id'])?
                        AttrValue::update($j,['id'=>$j['id']]):
                        AttrValue::create($j);
                }
            }else{
                $attrName = admin::create($v);
                $attrName->attrValue()->saveAll($v['attrValue']);
            }
        }
        return [HTTP_CREATED, "成功"];
    }

}
